import axios from 'axios'
import useToken from '@/store/token'
import { ElMessage } from 'element-plus'

const { token } = useToken()

const service = axios.create({
  baseURL: '/api',
  timeout: 5000
})

// 请求拦截器
service.interceptors.request.use(
  (config) => {
    if (token) {
      config.headers['Authorization'] = `Bearer ${token.token}`
    }
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

// 响应拦截器
service.interceptors.response.use(
  // 网络请求成功
  (response) => {
    const { code, msg, data } = response.data
    // 业务逻辑错误
    if (code !== 200) {
      ElMessage({
        message: msg || 'Error: 业务错误',
        type: 'warning'
      })
      return Promise.reject(new Error(msg || 'Error: 业务错误'))
    } else {
      return data
    }
  },
  // 网络请求失败
  (error) => {
    ElMessage.error(error.response?.data.msg || 'Error: 网络错误')
    return Promise.reject(error)
  }
)

export default service
